package com.kgc.web.servlet; /**
 * <h3>项目名称:demo03050</h3>
 * <p>本API描述:${description}</p>
 * <p>@author : AliyZhang</p>
 * <p>@date : 2021-03-08 12:53</p>
 **/

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.kgc.dao.UserDao;
import com.kgc.dao.impl.UserDaoImpl;
import com.kgc.entity.User;
import com.kgc.service.UserService;
import com.kgc.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UserServlet", value = "/user.do")
public class UserServlet extends HttpServlet {
    //private UserDao userDao=new UserDaoImpl();
    private UserService userService=new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*
        获取key的参数值，进而知道用户请求的功能
        key=exists  查询用户是否存在
        key=showOne  显示一个用户的信息
        key=showAll  显示全部的用户信息
         */
        String key=request.getParameter("key");
        switch (key){
            case "exists":
                exists(request,response);
                break;
            case "showOne":
                showOne(request,response);
                break;
            case "showAll":
                showAll(request,response);
                break;
        }

    }

    private void showAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //调用service方法，将查询到的用户信息存入list集合中
        List<User> list=userService.queryUsers();
        //把用户对象响应给前端即可。把用户对象转变为json型的字符串
        String listJsonStr= JSONArray.toJSONString(list);
        //System.out.println("listJsonStr="+listJsonStr);
        //服务器端向浏览器端响应数据
        response.getWriter().write(listJsonStr);
    }

    private void showOne(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取request请求时传来的参数
        int id=Integer.parseInt(request.getParameter("id"));
        //调用service方法，传id
        User user=userService.queryUserById(id);
        //把用户对象响应给前端即可。把用户对象转变为json型的字符串
        String userJsonStr= JSON.toJSONString(user);
        //System.out.println("userJsonStr="+userJsonStr);
        //把json型字符串响应给浏览器
        response.getWriter().write(userJsonStr);
    }

    private void exists(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取用户从前端传来的数据
        String userName = request.getParameter("userName");
        //调用userService的方法
        User user = userService.queryUserExistsByName(userName);
        //判断用户是否存在
        if(user==null){
            response.getWriter().write("no");
        }else {
            response.getWriter().write("yes");
        }
    }

}
